<template>
  <div>
    <div class="panel">
      <div class="panel-header">
        {{ $route.params.id ? $route.meta.title : '新增和能量' }}
      </div>
      <i-form
        ref="form"
        class="andEnergy-add_form"
        :items="formItems"
        :model="form"
        :rules="rules"
        :label-width="140"
        size="small"
      >
        <template slot="remark">
          <el-form-item>
            <div style="color: #988ca4">
              (注：默认无限天，自定义需大于等于7天)
            </div>
          </el-form-item>
        </template>
        <template slot="warning">
          <el-form-item>
            <div style="color: #988ca4">
              提示：和能量适用于本商户创建的所有电站，不支持下级运营商账号创建的电站
            </div>
          </el-form-item>
        </template>
      </i-form>
    </div>
    <div class="panel-btn-wrapper">
      <el-button type="success" v-loading="loading" @click="handleSubmit"
        >确认</el-button
      >
      <el-button type="warning" @click="handleCancel">取消</el-button>
    </div>
  </div>
</template>
<script>
import Big from 'big.js'
import formValidate from '@/utils/validate'
import { addAndEnergy, queryAndEnergyDetail, editAndEnergy } from '@/api/mySelf'

export default {
  name: 'AndEnergyAdd',
  methods: {
    handleCancel() {
      this.$router.push(this.from)
    },
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (!valid) return
        let params = Object.assign({}, this.form, {
          price: this.form.price * 100,
        })
        this.loading = true
        if (this.$route.params.id) {
          editAndEnergy({
            id: this.$route.params.id,
            ...params,
          })
            .then(() => {
              this.$message({
                type: 'success',
                showClose: true,
                message: '操作成功',
              })
              this.$router.push('/myself/andEnergy')
            })
            .catch((err) => {
              console.log(err)
            })
            .finally(() => {
              this.loading = false
            })
        } else {
          addAndEnergy(params)
            .then(() => {
              this.$message({
                type: 'success',
                showClose: true,
                message: '操作成功',
              })

              this.$router.push(this.from)
            })
            .catch((err) => {
              console.log(err)
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    },
  },
  async created() {
    if (this.$route.params.id) {
      let andEnergyDetail = await queryAndEnergyDetail({
        id: parseInt(this.$route.params.id),
      })
      // andEnergyDetail.effectiveDays = andEnergyDetail.effectiveDays
      //   ? andEnergyDetail.effectiveDays
      //   : undefined
      this.form = {
        energyAmount: andEnergyDetail.energyAmount,
        price: new Big(andEnergyDetail.price / 100).toFixed(2),
      }
      Object.assign(
        this.form,
        andEnergyDetail.effectiveDays && {
          effectiveDays: andEnergyDetail.effectiveDays,
        }
      )
      // this.form.price = new Big(this.form.price / 100).toFixed(2)
    }
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.from = from.fullPath
    })
  },
  data() {
    return {
      loading: false,
      type: 'add',
      from: '',
      formItems: [
        {
          label: '期限（天）',
          placeholder: '无限',
          type: 'inputNumber',
          value: 'effectiveDays',
          // class: 'andEnergy-el-input',
          span: 14,
          min: 7,
          max: 999,
        },
        {
          slot: 'remark',
        },
        {
          label: '包含和能量',
          type: 'inputNumber',
          span: 14,
          value: 'energyAmount',
          placeholder: '1元=100点和能量',
          min: 1,
          max: 99999,
        },
        {
          label: '价值（元）',
          type: 'detail',
          formatter: () => {
            return this.form.energyAmount
              ? new Big(this.form.energyAmount / 100)
              : '价值=能量点/100'
          },
        },
        {
          label: '售价（元）',
          type: 'inputNumber',
          // class: 'andEnergy-el-input',
          value: 'price',
          span: 14,
          placeholder: '充电用户购买的价格，精确到小数点后两位',
        },
        {
          slot: 'warning',
        },
      ],
      form: {},
      rules: {
        energyAmount: [
          {
            emptymsg: '请输入所包含和能量',
            required: true,
            type: 'number',
            trigger: 'blur',
            message: '请输入所包含和能量',
          },
          {
            trigger: ['change', 'blur'],
            validator: (rule, value, callback) => {
              value && this.form.price && this.$refs.form.validateField('price')
              callback()
            },
          },
        ],
        price: [
          {
            emptymsg: '请输入售价',
            required: true,
            type: 'number',
            trigger: 'blur',
            message: '请输入售价',
          },
          {
            validator: formValidate('validatePrecisionTwo'),
            trigger: 'blur',
          },
          {
            trigger: ['change', 'blur'],
            validator: (rule, value, callback) => {
              if (
                this.form.energyAmount &&
                value &&
                value > new Big(this.form.energyAmount / 100)
              ) {
                callback(new Error('售价需要小于价值'))
              } else {
                return callback()
              }
            },
          },
        ],
        effectiveDays: [
          {
            message: '需要大于等于7天',
            trigger: ['change', 'blur'],
            validator: (rule, value, callback) => {
              if (value && value < 7) {
                callback(new Error('需要大于等于7天'))
              } else {
                return callback()
              }
            },
          },
        ],
      },
    }
  },
}
</script>
<style lang="scss" scoped>
.andEnergy-add_form {
  width: 820px;

  .andEnergy-add_form_help {
    width: 20px;
    margin-left: 10px;
    cursor: pointer;
  }

  .andEnergy-add_form_power {
    margin-top: 8px;
    display: flex;
    align-items: center;
    height: 100%;
  }
}
.i-form {
  &::v-deep .el-form-item.is-error .el-transfer-panel__body .el-input__inner,
  .el-form-item.is-error .el-textarea__inner {
    border-color: #d9d9d9;
  }
  &::v-deep .el-form-item.is-error .el-transfer-panel {
    border-color: #ff4d4f;
  }
}
</style>
<style lang="scss">
.andEnergy-el-input {
  .el-input-number {
    width: 320px;
  }
}
</style>
